package com.wry.sharding.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;

/**
 * <h1> 按时间类型分片 <h1>
 *
 * @author wry
 * @since 2025/1/13 17:16
 */
@Slf4j
public class OrderShardingTableAlgorithm implements PreciseShardingAlgorithm<LocalDateTime> {

    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<LocalDateTime> shardingValue) {
        final LocalDateTime payTime = shardingValue.getValue();
        final int month = payTime.getMonth().getValue();
        String tableName = shardingValue.getLogicTableName() + payTime.getYear();
        if (month < 10) {
            tableName = tableName + "0" + month;
        } else {
            tableName = tableName + month;
        }
        log.info("拼接表名 = {}", tableName);
        if (tableNames.contains(tableName)) {
            return tableName;
        }
        log.error("取模精确分片策略：未找到与分片键匹配的表名! 逻辑表名[{}] : {} = {}", shardingValue.getLogicTableName(), shardingValue.getColumnName(), shardingValue.getValue());
        throw new UnsupportedOperationException();
    }
}
